<?php

namespace app\result;

use app\model\Feedback;
use app\model\user\User;

class FeedbackResult extends BaseResult
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Feedback();
    }

    public function feedback_list($user_id, $args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 50);
        $where = [];
        $where[] = ['user_id', '=', $user_id];
        if (!empty($args['keyword'])) {
            $where[] = ['content', 'like', '%' . trim($args['keyword']) . '%'];
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'id desc', $page, $pageSize);
        if ($data) {
            $data = $data->toArray();
            foreach ($data as &$item) {
                $item['status_text'] = $item['status'] == 0 ? '处理中' : '已处理';
                $item['title'] = (date('Y/m/d', strtotime($item['created_at']))) . ' ' . $item['type'];


                $item['images'] = array_filter(explode(',', $item['images']));

                if ($item['images']) {
                    $imageDiv = '';
                    for ($i = 0; $i < count($item['images']); $i++) {
                        $imageDiv .= '<img src="' . $item['images'][$i] . '" style="width: 100px;height: 100px;margin-right: 10px;">';
                    }
                    $item['content'] = $item['content'] . '<br>' . $imageDiv;
                }
                if ($item['reply']) {
                    $item['content'] = '<b >反馈内容</b>:' . $item['content'];
                    $item['content'] .= '<p style="height: 1px;border: 1px solid grey;margin-bottom: 8px;margin-top: 8px"></p>';
                    $item['content'] .= '<b >反馈回复</b>:' . htmlspecialchars_decode($item['reply']);
                }
                $item['content'] .= '<span style="margin-bottom: 10px"></span>';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    //留言反馈
    public function feedback($user_id, $args)
    {
        $rules = [
            ['content', 'empty|max:500|min:5', '反馈内容不能为空|反馈内容长度不能大于500|反馈内容长度不能小于5个字'],
            ['type', 'empty', '反馈类型不能为空']
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        if (!empty($args['image'])) {
            if (!is_array($args['image'])) {
                $args['image'] = explode(',', $args['image']);
            }
            if (count($args['image']) > 3) {
                return self::error_return('最多只能上传3张图片');
            }
            $args['image'] = implode(',', $args['image']);
        } else {
            $args['image'] = '';
        }
        $data = [
            'user_id' => $user_id,
            'content' => $args['content'],
            'type' => $args['type'],
            'images' => $args['image'] ?? '',
        ];

        $ckey = 'feedback_' . $user_id . '_' . $args['type'];
        if (!LockResult::logck_by_second($ckey, 5)) {
            return self::error_return('正在处理，请勿频繁提交');
        }

        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['status', '=', 0];
        $where[] = ['created_at', '>=', strtotime('today')];

        //每天只能5次反馈
        $count = $this->model->data_count($where);
        if ($count >= 5) {
            return self::error_return('每天只能提交5次反馈');
        }

        $where[] = ['content', '=', $args['content']];
        if ($this->model->data_count($where) > 0) {
            return self::error_return('您于' . date('Y-m-d H:i:s') . '的反馈已提交成功，我们会尽快处理，感谢您的支持！可以到反馈页面查看历史反馈查看处理进度。');
        }

        $res = (new Feedback())->data_add($data);
        if ($res) {
            UserMsgResult::add($user_id, [
                'title' => '反馈已提交',
                'content' => '您于' . date('Y-m-d H:i:s') . '的反馈已提交成功，我们会尽快处理，感谢您的支持！可以到反馈页面查看历史反馈查看处理进度。',
                'type' => 1,
                'path_info' => [
                    'title' => '反馈列表',
                    'path' => '/pages/setting/feedback',
                    'jump_type' => 'inner',//inner=内页，tab=底部导航，link=外链
                ],
            ]);
            if (config('email.admin_email')) {
                bs_queue(EmailResult::class, 'send_email', [
                    'email' => config('email.admin_email'),
                    'title' => '用户反馈',
                    'sub_title' => '用户反馈',
                    'content' => '用户反馈内容：' . $args['content'] . '<br>用户反馈图片：<br>' . implode('<br><br>', array_filter(explode(',', $args['image']))),
                ], time(), 2);
            }

        }

        return self::success_return('保存成功');
    }


    public function list($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['content', 'like', '%' . trim($args['keyword']) . '%'];
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'id desc', $page, $pageSize);
        if ($data) {
            $data = $data->toArray();
            $allUser = (new User())->data_list_nopage([['user_id', 'in', array_column($data, 'user_id')]], 'username,user_id');
            if ($allUser) {
                $allUser = array_column($allUser, null, 'user_id');
            }
            foreach ($data as &$item) {
                $item['images'] = array_filter(explode(',', $item['images']));
                $item['username'] = $allUser[$item['user_id']]['username'] ?? '【已注销】';
                $item['status_text'] = $item['status'] == 0 ? '未处理' : '已处理';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = [])
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['id' => $id]);
        return $this->success_return('success', $data);
    }

    public function save_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        if (empty($id)) {
            return $this->error_return('请选择要处理的反馈');
        }
        $model = new Feedback();
        $data = $model->data_get(['id' => $id]);
        if (empty($data) || $data['status'] == 1) {
            return $this->error_return('该反馈已处理');
        }
        $model->data_update(['id' => $id], ['status' => 1, 'reply' => $args['reply'] ?? '']);
        $content = '您于' . $data['created_at'] . '提交的【' . $data['type'] . '(' . $data['content'] . ')】已处理，感谢您的支持，感谢您的反馈！';
        if (!empty($args['reply'])) {
            $content .= '<br>处理结果：' . $args['reply'];
        }
        UserMsgResult::add($data['user_id'], [
            'title' => '反馈已处理',
            'content' => $content,
            'type' => 1,
            'path_info' => [
                'title' => '反馈列表',
                'path' => '/pages/setting/feedback',
                'jump_type' => 'inner',//inner=内页，tab=底部导航，link=外链
            ],
        ]);
        $email = (new User())->get_value(['user_id' => $data['user_id']], 'email');
        if (!empty($email)) {
            $email_data = [
                'title' => '反馈已处理',
                'content' => $content,
                'email' => $email
            ];
            bs_queue(EmailResult::class, 'send_email', $email_data);
        }
        return $this->success_return('success', '您于' . $data['created_at'] . '提交的反馈【' . $data['type'] . '】已处理，感谢您的反馈！');
    }

    public function del_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        $model = new Feedback();
        $res = $model->data_del(['id' => $id]);
        return $this->success_return('success');
    }
}
